package teehee.UI;

import java.util.ArrayList;

import teehee.Form.AddNewForm;
import teehee.Form.SearchPageForm;
import teehee.homepage.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

/**
 * @author Jun and Ashley
 * 
 */
public class AddNewWOD extends Activity {
	String[] repsTime = { "Reps", "Timed" };
	String repOrTimedSelection1 = "";
	String repOrTimedSelection2 = "";
	String repOrTimedSelection3 = "";
	String repOrTimedSelection4 = "";
	String repOrTimedSelection5 = "";
	int counter = 1;
	boolean errorRepFlag;
	boolean errorTimedFlag;
	boolean nameNullFlag;
	boolean nameInvalidFlag;
	boolean weightInvalidFlag;
	boolean exercise1NotExist;
	boolean exercise2NotExist;
	boolean exercise3NotExist;
	boolean exercise4NotExist;
	boolean exercise5NotExist;
	

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_new_wod);

		// set adapter for reps/time
		ArrayAdapter<String> repsOrTime = new ArrayAdapter<String>(this,
				R.layout.list_exercises, repsTime);

		// first rep/time
		Spinner sp1 = (Spinner) findViewById(R.id.spinnerRepsOrTime1);
		sp1.setAdapter(repsOrTime);
		sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				Object item = parent.getItemAtPosition(pos);
				repOrTimedSelection1 = item.toString();
			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		Button addMoreExercise = (Button) findViewById(R.id.addNewExerciseForWOD);
		addMoreExercise.setOnClickListener(new AddMoreExerciseButtonHandler());

		Button submit = (Button) findViewById(R.id.submitNewWODButton);
		submit.setOnClickListener(new SubmitHandler());
	}

	private class AddMoreExerciseButtonHandler implements OnClickListener {
		ArrayAdapter<String> repsOrTime = new ArrayAdapter<String>(
				AddNewWOD.this, R.layout.list_exercises, repsTime);

		public void onClick(View v) {
			switch (counter) {
			case 1:
				EditText exercise2 = (EditText) findViewById(R.id.exercise2);
				exercise2.setVisibility(EditText.VISIBLE);
				Spinner sp2 = (Spinner) findViewById(R.id.spinnerRepsOrTime2);
				sp2.setAdapter(repsOrTime);
				sp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						Object item = parent.getItemAtPosition(pos);
						repOrTimedSelection2 = item.toString();
					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
				((LinearLayout) findViewById(R.id.LayoutRepsTime2))
						.setVisibility(LinearLayout.VISIBLE);
				((LinearLayout) findViewById(R.id.weight2))
				.setVisibility(LinearLayout.VISIBLE);
				counter++;
				break;

			case 2:
				EditText exercise3 = (EditText) findViewById(R.id.exercise3);
				exercise3.setVisibility(EditText.VISIBLE);
				Spinner sp3 = (Spinner) findViewById(R.id.spinnerRepsOrTime3);
				sp3.setAdapter(repsOrTime);
				sp3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						Object item = parent.getItemAtPosition(pos);
						repOrTimedSelection3 = item.toString();
					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
				((LinearLayout) findViewById(R.id.LayoutRepsTime3))
						.setVisibility(LinearLayout.VISIBLE);
				((LinearLayout) findViewById(R.id.weight3))
				.setVisibility(LinearLayout.VISIBLE);
				counter++;
				break;

			case 3:
				EditText exercise4 = (EditText) findViewById(R.id.exercise4);
				exercise4.setVisibility(EditText.VISIBLE);
				Spinner sp4 = (Spinner) findViewById(R.id.spinnerRepsOrTime4);
				sp4.setAdapter(repsOrTime);
				sp4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						Object item = parent.getItemAtPosition(pos);
						repOrTimedSelection4 = item.toString();
					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
				((LinearLayout) findViewById(R.id.LayoutRepsTime4))
						.setVisibility(LinearLayout.VISIBLE);
				((LinearLayout) findViewById(R.id.weight4))
				.setVisibility(LinearLayout.VISIBLE);
				counter++;
				break;

			case 4:
				EditText exercise5 = (EditText) findViewById(R.id.exercise5);
				exercise5.setVisibility(EditText.VISIBLE);
				Spinner sp5 = (Spinner) findViewById(R.id.spinnerRepsOrTime5);
				sp5.setAdapter(repsOrTime);
				sp5.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						Object item = parent.getItemAtPosition(pos);
						repOrTimedSelection5 = item.toString();
					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
				((LinearLayout) findViewById(R.id.LayoutRepsTime5))
						.setVisibility(LinearLayout.VISIBLE);
				((LinearLayout) findViewById(R.id.weight5))
				.setVisibility(LinearLayout.VISIBLE);
				counter++;
				break;

			default:
				toaster("Too many exercises");
				break;
			}
		}
	}

	private class SubmitHandler implements OnClickListener {
		public void onClick(View v) {
			errorRepFlag = false;
			errorTimedFlag = false;
			nameNullFlag = false;
			nameInvalidFlag = false;
			weightInvalidFlag = false;
			exercise1NotExist = false;
			exercise2NotExist = false;
			exercise3NotExist = false;
			exercise4NotExist = false;
			exercise5NotExist = false;
			
			EditText inputName = (EditText) findViewById(R.id.enterNewWODName);
			EditText inputTimeOrRep1 = (EditText) findViewById(R.id.enterRepsOrTime1);
			EditText inputTimeOrRep2 = (EditText) findViewById(R.id.enterRepsOrTime2);
			EditText inputTimeOrRep3 = (EditText) findViewById(R.id.enterRepsOrTime3);
			EditText inputTimeOrRep4 = (EditText) findViewById(R.id.enterRepsOrTime4);
			EditText inputTimeOrRep5 = (EditText) findViewById(R.id.enterRepsOrTime5);
			
			EditText inputDesciption = (EditText) findViewById(R.id.WOD_description);
			
			String name = inputName.getText().toString().trim();
			String input1 = inputTimeOrRep1.getText().toString().trim();
			String input2 = inputTimeOrRep2.getText().toString().trim();
			String input3 = inputTimeOrRep3.getText().toString().trim();
			String input4 = inputTimeOrRep4.getText().toString().trim();
			String input5 = inputTimeOrRep5.getText().toString().trim();
			
			EditText exercise1 = (EditText) findViewById(R.id.exercise1);
			EditText exercise2 = (EditText) findViewById(R.id.exercise2);
			EditText exercise3 = (EditText) findViewById(R.id.exercise3);
			EditText exercise4 = (EditText) findViewById(R.id.exercise4);
			EditText exercise5 = (EditText) findViewById(R.id.exercise5);
			
			EditText enterWeight1 = (EditText) findViewById(R.id.enterWeight1);
			EditText enterWeight2 = (EditText) findViewById(R.id.enterWeight2);
			EditText enterWeight3 = (EditText) findViewById(R.id.enterWeight3);
			EditText enterWeight4 = (EditText) findViewById(R.id.enterWeight4);
			EditText enterWeight5 = (EditText) findViewById(R.id.enterWeight5);
			
			String weight1 = enterWeight1.getText().toString().trim();
			String weight2 = enterWeight2.getText().toString().trim();
			String weight3 = enterWeight3.getText().toString().trim();
			String weight4 = enterWeight4.getText().toString().trim();
			String weight5 = enterWeight5.getText().toString().trim();
			ArrayList<String> exercises = new ArrayList<String>();


			int nameValidation = AddNewForm.validateName(name);
			if (nameValidation == -1) {
				nameNullFlag = true;
			} else if(nameValidation == 0){
				nameInvalidFlag = true;
			}
			
			// make validation for timed/reps
			if (!AddNewForm.determineMeasurement(repOrTimedSelection1)) {
				if (!AddNewForm.validateMeasurement("Timed", input1)) {
					errorTimedFlag = true;
				}
			} else {
				if (!AddNewForm.validateMeasurement("Reps", input1)) {
					errorRepFlag = true;
				}
			}

			if (!AddNewForm.determineMeasurement(repOrTimedSelection2) && counter > 1) {
				if (!AddNewForm.validateMeasurement("Timed", input2)) {
					errorTimedFlag = true;
				}
			} else if (AddNewForm.determineMeasurement(repOrTimedSelection2) && counter > 1){
				if (!AddNewForm.validateMeasurement("Reps", input2)) {
					errorRepFlag = true;
				}
			}
			
			if (!AddNewForm.determineMeasurement(repOrTimedSelection3) && counter > 2) {
				if (!AddNewForm.validateMeasurement("Timed", input3)) {
					errorTimedFlag = true;
				}
			} else if (AddNewForm.determineMeasurement(repOrTimedSelection2) && counter > 2){
				if (!AddNewForm.validateMeasurement("Reps", input3)) {
					errorRepFlag = true;
				}
			}
			
			if (!AddNewForm.determineMeasurement(repOrTimedSelection4) && counter > 3) {
				if (!AddNewForm.validateMeasurement("Timed", input4)) {
					errorTimedFlag = true;
				}
			} else if (AddNewForm.determineMeasurement(repOrTimedSelection2) && counter > 3){
				if (!AddNewForm.validateMeasurement("Reps", input4)) {
					errorRepFlag = true;
				}
			}
			
			if (!AddNewForm.determineMeasurement(repOrTimedSelection5) && counter > 4) {
				if (!AddNewForm.validateMeasurement("Timed", input5)) {
					errorTimedFlag = true;
				}
			} else if (AddNewForm.determineMeasurement(repOrTimedSelection2) && counter > 4){
				if (!AddNewForm.validateMeasurement("Reps", input5)) {
					errorRepFlag = true;
				}
			}
			
			if(AddNewForm.AddNewFormFind(exercise1.getText().toString().trim()) == null) {
				exercise1NotExist = true;
			}
			if(AddNewForm.AddNewFormFind(exercise1.getText().toString().trim()) == null && counter > 1) {
				exercise2NotExist = true;
			}
			if(AddNewForm.AddNewFormFind(exercise1.getText().toString().trim()) == null && counter > 2) {
				exercise3NotExist = true;
			}
			if(AddNewForm.AddNewFormFind(exercise1.getText().toString().trim()) == null && counter > 3) {
				exercise4NotExist = true;
			}
			if(AddNewForm.AddNewFormFind(exercise1.getText().toString().trim()) == null && counter > 4) {
				exercise5NotExist = true;
			}
			
			//make validation for weight
			if (!AddNewForm.validateWeight(weight1)) {
				weightInvalidFlag = true;
			}
			
			if (!AddNewForm.validateWeight(weight2) && counter > 1) {
				weightInvalidFlag = true;
			}
			
			if (!AddNewForm.validateWeight(weight3) && counter > 2) {
				weightInvalidFlag = true;
			}
			
			if (!AddNewForm.validateWeight(weight4) && counter > 3) {
				weightInvalidFlag = true;
			}
			
			if (!AddNewForm.validateWeight(weight5) && counter > 4) {
				weightInvalidFlag = true;
			}
			
			//pop out error message
			if(nameNullFlag){
				toaster("Name cannot be empty");
			}
			if(nameInvalidFlag){
				toaster("Name cannot contain special characters");
			}
			if(exercise1NotExist) {
				toaster("Exercise 1 is not found");
			}
			if(exercise2NotExist) {
				toaster("Exercise 2 is not found");
			}
			if(exercise3NotExist) {
				toaster("Exercise 3 is not found");
			}
			if(exercise4NotExist) {
				toaster("Exercise 4 is not found");
			}
			if(exercise5NotExist) {
				toaster("Exercise 5 is not found");
			}
			else if (errorRepFlag) {
				toaster("Reps field is empty or it is not in the correct format");
			}
			else if(errorTimedFlag)
			{
				toaster("Time must be in format ':ss', 'mm:ss', 'hh:mm:ss'.  No fields may exceed 60.");
			}
			else if(weightInvalidFlag) {
				toaster("Weight can only be number");
			}
			

			
			//add exercises into the list
			if (weight1.equals("") || weight1 == null) {
				exercises.add(input1 + " " + exercise1.getText().toString().trim() + " " + weight1);
			} else {
				exercises.add(input1 + " " + exercise1.getText().toString().trim() + " " + weight1 + "lbs");
			}
			
			if (counter > 1) {
				if (weight2.equals("") || weight2 == null) {
					exercises.add(input2 + " " + exercise2.getText().toString().trim() + " " + weight2);
				} else {
					exercises.add(input2 + " " + exercise2.getText().toString().trim() + " " + weight2 + "lbs");
				}
			}
			
			if (counter > 2) {
				if (weight3.equals("") || weight3 == null) {
					exercises.add(input3 + " " + exercise3.getText().toString().trim() + " " + weight3);
				} else {
					exercises.add(input3 + " " + exercise3.getText().toString().trim() + " " + weight3 + "lbs");
				}
			}
			
			if (counter > 3) {
				if (weight4.equals("") || weight4 == null) {
					exercises.add(input4 + " " + exercise4.getText().toString().trim() + " " + weight4);
				} else {
					exercises.add(input4 + " " + exercise4.getText().toString().trim() + " " + weight4 + "lbs");
				}
			}
			
			if (counter > 4) {
				if (weight5.equals("") || weight5 == null) {
					exercises.add(input5 + " " + exercise5.getText().toString().trim() + " " + weight5);
				} else {
					exercises.add(input5 + " " + exercise5.getText().toString().trim() + " " + weight5 + "lbs");
				}
			}
			
			//if there is no error for validation
			if (nameValidation == 1 && !errorRepFlag && !errorTimedFlag && !exercise1NotExist && !exercise2NotExist
					&& !exercise3NotExist && !exercise4NotExist && !exercise5NotExist) {
				boolean result = AddNewForm.createNewEntryForm(getApplicationContext(), "wod", name, "0", "0", "0",
								 inputDesciption.getText().toString().trim(), exercises);
				if (result == false) {
					toaster("Name has been already used");
					return;
				} else {
					toaster("WOD has been successfully added");
				}
			} else {
				return; // keep all the fields that user has input
			}
/*
			// Clear all the field and hide the extra exercise fields.
			inputName.setText(null);
			((EditText) findViewById(R.id.WOD_description)).setText(null);

			exercise1.setText(null);
			inputTimeOrRep1.setText(null);
			enterWeight1.setText(null);

			exercise2.setText(null);
			exercise2.setVisibility(EditText.GONE);
			((Spinner) findViewById(R.id.spinnerRepsOrTime2)).setVisibility(Spinner.GONE);
			inputTimeOrRep2.setVisibility(LinearLayout.GONE);
			inputTimeOrRep2.setText(null);
			((TextView) findViewById(R.id.exercise2weight)).setVisibility(TextView.GONE);
			enterWeight2.setVisibility(EditText.GONE);
			enterWeight2.setText(null);

			exercise3.setText(null);
			exercise3.setVisibility(EditText.GONE);
			((Spinner) findViewById(R.id.spinnerRepsOrTime3)).setVisibility(Spinner.GONE);
			inputTimeOrRep3.setVisibility(LinearLayout.GONE);
			inputTimeOrRep3.setText(null);
			((TextView) findViewById(R.id.exercise3weight)).setVisibility(TextView.GONE);
			enterWeight3.setVisibility(EditText.GONE);
			enterWeight3.setText(null);

			exercise4.setText(null);
			exercise4.setVisibility(EditText.GONE);
			((Spinner) findViewById(R.id.spinnerRepsOrTime4)).setVisibility(Spinner.GONE);
			inputTimeOrRep4.setVisibility(LinearLayout.GONE);
			inputTimeOrRep4.setText(null);
			((TextView) findViewById(R.id.exercise4weight)).setVisibility(TextView.GONE);
			enterWeight4.setVisibility(EditText.GONE);
			enterWeight4.setText(null);

			exercise5.setText(null);
			exercise5.setVisibility(EditText.GONE);
			((Spinner) findViewById(R.id.spinnerRepsOrTime5)).setVisibility(Spinner.GONE);
			inputTimeOrRep5.setVisibility(LinearLayout.GONE);
			inputTimeOrRep5.setText(null);
			((TextView) findViewById(R.id.exercise5weight)).setVisibility(TextView.GONE);
			enterWeight5.setVisibility(EditText.GONE);
			enterWeight5.setText(null);*/
			
			AddNewTabs.entry = SearchPageForm.processInput(name);
			AddNewTabs.goHistoryPage = true;
			Intent history = new Intent(AddNewWOD.this, ExerciseHistory.class);
    		startActivity(history);
			
			counter = 1;
		}
	}
	public void toaster(String errormessage)
	{

		Context context = getApplicationContext();
		Toast toast = Toast.makeText(context, errormessage, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.TOP|Gravity.LEFT, 25, 300);
		toast.show();
		
	}
	
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        if ((keyCode == KeyEvent.KEYCODE_MENU))
        { 
        	//setContentView(R.layout.main);
        	Intent homep = new Intent(AddNewWOD.this, MainPage.class);
    		startActivity(homep);
            return true;
        }
        
        if ((keyCode == KeyEvent.KEYCODE_SEARCH))
        { 
        	//setContentView(R.layout.main);
        	Intent homep = new Intent(AddNewWOD.this, SearchPage.class);
    		startActivity(homep);
            return true;
        }
        
        return super.onKeyDown(keyCode, event);    
    } 

}
